package cc.mrbird.febs.server.referral.controller;

import cc.mrbird.febs.common.core.entity.FebsResponse;
import cc.mrbird.febs.common.core.entity.ResponseCode;
import cc.mrbird.febs.common.core.exception.FebsException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;

/**
 * 图片上传接口
 * @author
 * @version 1.0
 * @ClassName UploadImagesController
 * @Description TODO
 * @date 2020/6/22 11:17
 */
@Slf4j
@Validated
@Controller
@Api(value = "UploadImagesController", description = "上传图片接口")
@RequestMapping("/uic")
@RequiredArgsConstructor
public class UploadImagesController {

    @Value("${wx.upload_file_url}")
    private String imageUploadUrl;

    @Value("${wx.upload_file_path}")
    private String imageUploadPath;


    /**
     * 上传图片接口
     * */
    @PostMapping("/upload")
    @ApiOperation(value = "上传图片接口", notes = "上传图片接口")
    @ResponseBody
    public FebsResponse upload(String filename, MultipartFile file, HttpServletRequest request) throws FebsException {
        FebsResponse febsResponse = new FebsResponse();
        BufferedOutputStream stream = null;
        String suffix = null;
        if (!file.isEmpty()) {
            try {
                int index = file.getOriginalFilename().lastIndexOf('.');
                if (index >= 0) {
                    //取出文件后缀 suffix 释义 后缀
                    suffix = file.getOriginalFilename().substring(index);
                    String[] suffixs = {".jpg",".bmp",".png",".jpeg"};
                    boolean flag = false;
                    for (String s : suffixs) {
                        if (s.equals(suffix)) {
                            flag = true;
                            break;
                        }
                    }
                    if (flag) {
                        byte[] bytes = file.getBytes();
                        String newFilePath = "";
                        if (imageUploadPath.contains("classpath:")) {
                            newFilePath = ClassLoader.getSystemResource(imageUploadPath.substring("classpath:".length())).toString().substring("file:/".length());
                        } else {
                            newFilePath = imageUploadPath;
                        }
                        log.info("上传图片地址：{}", newFilePath);
                        File temp = new File(newFilePath + filename + suffix);
                        if (temp.exists()) {
                            temp.delete();
                        }
                        File pathfile=new File(newFilePath);
                        if (!pathfile.exists()){
                            pathfile.mkdirs();
                        }
                        temp = new File(newFilePath + filename + suffix);
                        temp.createNewFile();
                        stream = new BufferedOutputStream(new FileOutputStream(temp));
                        stream.write(bytes);
                        stream.close();
                    } else {
                        throw new FebsException("文件格式不正确");
                    }
                } else {
                    throw new FebsException("文件没有后缀");
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new FebsException("文件获取失败");
            }
        } else {
            febsResponse.code(ResponseCode.WRONG.getCode());
            febsResponse.message("上传的非要求文件");
            return febsResponse;
        }
        String finalSuffix = suffix;
//        String requestUrl = request.getRequestURL().toString();
//        Integer last = requestUrl.lastIndexOf("upload");
//        String url = requestUrl.substring(0, last) + "show/"+ filename + finalSuffix;
        String url = this.imageUploadUrl + filename + finalSuffix;
//        String url = "http://"+request.getServerName() + ":" + request.getServerPort() + request.getContextPath()  +"/image/show/"+ filename + finalSuffix;

        log.info("上传图片url：{}", url);
        HashMap dataMap = new HashMap<String, String>(){{
            put("file_name", filename);
            put("file_url", url);
        }};
        febsResponse.code(ResponseCode.SUCCESS.getCode());
        febsResponse.data(dataMap);
        return febsResponse;
    }

    /**
     * 显示图片
     * */
    @ApiOperation(value = "显示图片", notes = "显示图片")
    @GetMapping("/show/{image_name}")
    public void returnImage(@PathVariable("image_name") String imageName, HttpServletResponse response) throws IOException {
        String imagePath = imageUploadPath + imageName;
        File file = new File(imagePath);
        if (!file.exists()) {
            throw new IOException("图片不存在");
        }

        response.setContentType("image/png");
        ServletOutputStream outputStream = response.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream(file);
        int count = 0;
        byte[] buffer = new byte[1024 * 8];
        while ((count = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, count);
            outputStream.flush();
        }
        outputStream.close();
    }
}
